//
//  UITextView+Emoticon.swift
//  1 - 表情处理
//
//  Created by sanya on 15/7/8.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
extension UITextView {

    ///  插入表情符号
    func insertEmoticon(emoticon:Emoticon) {
        // 1. emoji
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji ?? "")
        }
        // 2. 表情符号
        if emoticon.chs != nil {
            // 1. NSTextAttachment 图片的附件
            let attachment = EmoticonAttachment()
            // 记录表情符号的文本
            attachment.chs = emoticon.chs
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
            let s = font!.lineHeight
            attachment.bounds = CGRectMake(0, -4, s, s)
            // 2. 生成一个属性文本
            let imageText = NSAttributedString(attachment: attachment)
            // 3. 获得文本框完整的文本
            let strM = NSMutableAttributedString(attributedString: attributedText)
            strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            // 4. 将属性文本，重新设置给 textView
            // 4.1 记录光标的位置
            let range = selectedRange
            // 4.2 设置表情图片的字体
            strM.addAttributes([NSFontAttributeName:font!], range: NSMakeRange(range.location, 1))
            // 4.3 设置文本
            attributedText = strM
            // 4.4 恢复光标位置
            selectedRange = NSMakeRange(range.location + 1, 0)
        }
        
    }
    func emoticonText() -> String {
        print("ok")
        // 定义结果字符串
        var strM = String()
        // 遍历内部细节
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            print("-----")
            //            print(dict)
            //            print(range)
            // 如果字典中包含 NSAttachment key 就说明是图片
            // 新问题：如何从 `NSAttachment` 中获取到 表情的文本？ - 继承一个子类，专门记录表情
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("配图\(attachment.chs)")
                strM += attachment.chs ?? ""
            }else {
                let str = (self.attributedText.string as String as NSString).substringWithRange(range)
                print("文本内容" + str)
                strM += str
            }
        }
        return strM
    }


    
}
